let tableIns;
let tree;
layui.use(['table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    tree = layui.tree;
    let laydate = layui.laydate;
    let form = layui.form;
    let height = document.documentElement.clientHeight - 60;

    findMoney();
    
    tableIns = table.render({
        elem: '#invoiceTable'
        , url: '/seller/bill/list/page'
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            // console.log("data=="+data);
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: true
        , title: '企业开票'
        , cols: [[
            {field: 'sellerCompanyName', title: '公司名字'}
            , {field: 'taxPayerCode', title: '纳税人识别号'}
            , {field: 'taxableTotal',title: '开票金额',templet:money}
            , {field: 'billContent', title: '开票备注'}
            , {field: 'expressCode', title: '快递单号'}
            , {field: 'realRecivePersonName', title: '收件人'}
            , {field: 'mobile', title: '收件人手机'}
            , {field: 'address', title: '收件人地址'}
            , {field: 'createTime', title: '申请时间'}
            ,  {field: 'status',title: '发票状态' ,toolbar: '#staBar1'}
        ]]
        , defaultToolbar: ['', '', '']
        , page: true
        , height: height
        , cellMinWidth: 80
    });
    
    
    form.on('submit(menu-query)', function (data) {
    	
      	 // 搜索条件
          var sellerCompanyName=data.field.sellerCompanyName;
          var status=data.field.status;
          var startDate=data.field.startDate;
          var endDate=data.field.endDate;
          	// var tel=$("#tel").val();
              table.reload('invoiceTable', {
                  url:'/platform/grant/queryBilling'
                  , where: {
                      'sellerCompanyName':sellerCompanyName,
                      'status':status,
                      'startDate':startDate,
                      'endDate':endDate,
                  }
                  , page: {
                      curr: 1
                  }
              });
              findMoney();
              return false;
          
     });
       
       
       //日期选择器
       startDateIns = laydate.render({
           elem: '#queryByStartDate',
           format: "yyyy-MM-dd",
           trigger: 'click'
       });

       
       //日期选择器
       endDateIns = laydate.render({
           elem: '#queryByEndDate',
           format: "yyyy-MM-dd",
           trigger: 'click'
       });



});


function money(d){
	let number = d.taxableTotal;
	number = number.toString().replace(/\,/g, "");
	if(isNaN(number) || number == "")return "";
	number = Math.round(number * 100) / 100;
	    if (number < 0)
	        return '-' + outputdollars(Math.floor(Math.abs(number) - 0) + '') + outputcents(Math.abs(number) - 0);
	    else
	        return outputdollars(Math.floor(number - 0) + '') + outputcents(number - 0);
	} 
	//格式化金额
	function outputdollars(number) {
	    if (number.length <= 3)
	        return (number == '' ? '0' : number);
	    else {
	        var mod = number.length % 3;
	        var output = (mod == 0 ? '' : (number.substring(0, mod)));
	        for (i = 0; i < Math.floor(number.length / 3); i++) {
	            if ((mod == 0) && (i == 0))
	                output += number.substring(mod + 3 * i, mod + 3 * i + 3);
	            else
	                output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
	        }
	        return (output);
	    }
	}
	function outputcents(amount) {
	    amount = Math.round(((amount) - Math.floor(amount)) * 100);
	    return (amount < 10 ? '.0' + amount : '.' + amount);
	}

function show_img(t) {
    var t = $(t).find("img");
    //页面层
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['80%', '80%'], //宽高
        shadeClose: true, //开启遮罩关闭
        end: function (index, layero) {
            return false;
        },
        content: '<div style="text-align:center"><img src="' + $(t).attr('src') + '" /></div>'
    });
}

function formatMoney(str) {
    if (!str) str = '0.00';
    let ret = Math.round(parseFloat(str) * 100) / 100;
    let decimal = ret.toString().split('.');
    if (decimal.length === 1) {
        return ret.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            + '.00';
    };
    if (decimal.length > 1) {
        decimal[0] = decimal[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        if (decimal[1].length < 2) {
            decimal[1] += '0';
            return decimal.join(".");
        }
        return decimal.join(".");
    };
    return ret;
}


function findMoney(){
    $.post('/seller/bill/findBybill?sellerCompanyName='+ $("#sellerCompanyName").val() + "&status=" + $("#status").val() + "&startDate=" + $("#queryByStartDate").val() +"&endDate=" + $("#queryByEndDate").val() , {}, function (data) {
    			
                $("#sum_money1").html("待开总金额："+formatMoney(data.data[0].examineing));
                $("#sum_money2").html("已开总金额："+formatMoney(data.data[0].examineed));
                $("#sum_money3").html("待开张数："+data.data[0].billing);
                $("#sum_money4").html("已开张数："+data.data[0].billed);
    })
}